package com.guaika.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guaika.reggie.common.ResultMessage;
import com.guaika.reggie.common.StringChars;
import com.guaika.reggie.entity.User;
import com.guaika.reggie.mapper.UserMapper;
import com.guaika.reggie.service.UserService;
import com.guaika.reggie.utils.RedisCacheUtils;
import com.guaika.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author GuaiKa
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisCacheUtils redisTemplate;

    private static final int max = 2;

    @Override
    public ResultMessage<String> sendMsg(User user, HttpSession session) {
        String timeliness = "timeliness" + user.getPhone();
        //设置自增
        Long aLong = redisTemplate.incrBy(timeliness, 1);
        //更新值大于2则证明当前访问过于频繁
        if (aLong>max) {
            return ResultMessage.error(StringChars.SEND_CODE_MESSAGE_OFTEN.getStr());
        }
        redisTemplate.expire(timeliness, 1, TimeUnit.SECONDS);
        String phone = user.getPhone();
        //判断验证码是否存在
        Boolean exists = redisTemplate.exists(phone);
        if (exists) {
            return ResultMessage.error(StringChars.SEND_CODE_MESSAGE_EXIST.getStr());
        }
        //验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code:{}", code);
        //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
        redisTemplate.setEx(phone, code, 5, TimeUnit.MINUTES);
        return ResultMessage.success(StringChars.SEND_CODE_MESSAGE.getStr());
    }

    @Override
    public ResultMessage<User> login(Map map, HttpSession session) {
        String phone = map.get("phone").toString();
        String reCode = map.get("code").toString();
        //获取redis中存的验证码
        String code = redisTemplate.get(phone);
        //比对验证码
        if (code != null && reCode.equals(code)) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = this.getOne(lambdaQueryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                this.save(user);
            }
            session.setAttribute(StringChars.User.getStr(), user.getId());
            return ResultMessage.success(user);
        }
        return ResultMessage.error(StringChars.ACCOUNT_ERROR.getStr());
    }
}
